import SingletonMessage from "@/utils/message";
/**
 * 防止重复提交拦截器
 *
 */
class RepeatSubmitInterceptor {
  #requestCache;
  constructor() {
    this.#requestCache = new RequestCache();
  }
  request(config) {
    if (this.#requestCache.has(config)) {
      const message = "请求频繁，请稍后重试";
      SingletonMessage.error(message);
      return Promise.reject(message);
    }
    this.#requestCache.set(config);
    return config;
  }
  response(config) {
    this.#requestCache.delete(config);
    return config;
  }
}

class RequestCache {
  #cache;
  constructor() {
    this.#cache = new Map();
  }
  #key(config) {
    return `${config.method}:${config.url}`;
  }
  set(config) {
    this.#cache.set(this.#key(config), config);
  }
  delete(config) {
    this.#cache.delete(this.#key(config));
  }
  has(config) {
    return this.#cache.has(this.#key(config));
  }
}

const repeatSubmitInterceptor = new RepeatSubmitInterceptor();
export default repeatSubmitInterceptor;
